# -*-coding:utf-8 -*-
import struct
from protobuf.protocol import type1_pb2, type2_pb2, type3_pb2, type4_pb2, type5_pb2


def rev_msg(message):
    # 请求id
    request_id = message[:4]
    request_id = request_id[::-1]
    request_id = struct.unpack('i', request_id)[0]
    print "request_id:", request_id
    # userID
    to_user_id = message[4:8]
    to_user_id = to_user_id[::-1]
    to_user_id = struct.unpack('i', to_user_id)[0]
    print "to_user_id:", to_user_id

    # 接收请求消息
    proto = message[8:]
    print_pro_msg(proto, request_id)

    return to_user_id


# 打印主题消息
def print_pro_msg(proto, request_id):
    if request_id == 1:
        msg = type1_pb2.ParentModule()
        msg.ParseFromString(proto)
        print "=====接收type1===="
        print msg.name
        print msg.number
        for m in msg.childrenModule:
            print m.name
            print m.number
        print "=====接收end====="
    if request_id == 2:
        msg = type2_pb2.ParentModule()
        msg.ParseFromString(proto)
        print "=====接收type2===="
        print msg.username
        print msg.password
        print "=====接收end====="
    if request_id == 3:
        msg = type3_pb2.ChildrenModule()
        msg.ParseFromString(proto)
        print "=====接收type3===="
        print msg.groupname
        print msg.groupid
        print "=====接收end====="
    if request_id == 4:
        msg = type4_pb2.ChildrenModule()
        msg.ParseFromString(proto)
        print "=====接收type3===="
        print msg.groupname
        print msg.groupid
        print msg.grouptype
        print "=====接收end====="
    if request_id == 5:
        msg = type5_pb2.ParentModule()
        msg.ParseFromString(proto)
        print "=====接收type2===="
        print msg.group
        print msg.type
        print "=====接收end====="


def create_pro_from_pro(message, from_user_id):
    # 请求id
    request_id = message[:4]
    from_user_id = int(from_user_id)
    from_user_id = create_msg_id(from_user_id)
    msg_pro = message[8:]
    return request_id + from_user_id + msg_pro


def create_pro_msg(requst_id):
    # 父模块
    its = type1_pb2.ParentModule()
    its.number = 5
    its.name = "father"
    # 子模块1
    son1 = its.childrenModule.add()
    son1.number = 7
    son1.name = "son1"

    its_str = its.SerializeToString()

    req_id = create_msg_id(requst_id)
    return req_id + its_str


def create_msg_id(request_id):
    req_id = struct.pack("i", request_id)
    return req_id[::-1]